package cn.jji8.patternLogin.spigot.login;

import cn.jji8.patternLogin.spigot.data.Data;
import cn.jji8.patternLogin.spigot.PatternLogin;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;

import java.util.HashMap;
import java.util.Map;

/**
 * 用于合理显示登录时消息的类
 * */
public class LoginNews {
    static final Map<Player,LoginNews> PlayerLoginNews = new HashMap<>();
    public static void load() {
        Bukkit.getScheduler().runTaskTimerAsynchronously(PatternLogin.getMain(), LoginNews::staticRun, 1, 1);
    }
    /**
     * 调用全部的玩家消息显示器
     * */
    static void staticRun(){
        for (LoginNews value : PlayerLoginNews.values()) {
            value.run();
        }
    }
    /**
     * 为一个未登录的玩家发送消息，持续一段时间
     * */
    static void news(Player player,String news,int time){
        LoginNews loginNews = PlayerLoginNews.get(player);
        if(loginNews==null){
            PlayerLoginNews.put(player,loginNews = new LoginNews(player));
        }
        loginNews.news(news,time);
    }
    /**
     * 设置一个玩家的长显示消息
     * */
    static void longNews(Player player,String news){
        LoginNews loginNews = PlayerLoginNews.get(player);
        if(loginNews==null){
            PlayerLoginNews.put(player,loginNews = new LoginNews(player));
        }
        loginNews.setLongDisplayNews(news);
    }
    /**
     * 登录之前
     * */
    static void loginAfter(Player player) {
        LoginNews loginNews = PlayerLoginNews.get(player);
        if(loginNews==null){
            PlayerLoginNews.put(player,new LoginNews(player));
        }
    }
    /**
     * 登录之后
     * */
    static void loginBefore(Player player) {
        LoginNews loginNews = PlayerLoginNews.remove(player);
        if(loginNews!=null){
            loginNews.run();
        }
    }
    /**
     * 玩家离开服务器
     * */
    static void PlayerLeave(Player player){
        PlayerLoginNews.remove(player);
        Bukkit.getScheduler().runTaskAsynchronously(PatternLogin.getMain(), () -> Data.setLocation(player.getName(),player.getLocation()));

    }

    //·······················································
    //实例方法
    final Player player;
    String news = " ";
    String loginDisplayNews = " ";
    int time = 0;
    @SuppressWarnings("unused")
    LoginNews(Player player){
        this.player = player;
    }
    /**
     * 设置长留消息
     * */
    void setLongDisplayNews(String news){
        loginDisplayNews = news;
    }
    /**
     * 显示某消息一段时间
     * **/
    void news(String news,int time){
        this.news = news;
        this.time = time;
    }
    void run(){
        if(time >0){
            time--;
            player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(news));
        }else {
            player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(loginDisplayNews));
        }
    }
}
